import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Row, Col, Button } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictIndexList from './DictIndexList';
import DictIndexModal from './DictIndexModal';
import DictValueList from './DictValueList';
import DictValueModal from './DictValueModal';

@connect(({ dictIndex, dictValue }) => ({
  dictIndex,
  dictValue,
}))
class Dict extends PureComponent {
  handleOpenIndexModal = data => {
    const { dispatch } = this.props;
    dispatch({ type: 'dictIndex/openModal', payload: data || {} });
  };

  handleSubmitIndexModal = values => {
    const { dispatch } = this.props;
    if (values.id) {
      dispatch({ type: 'dictIndex/fetch' });
    } else {
      dispatch({ type: 'dictIndex/reload' });
    }
  };

  handleViewIndexValues = record => {
    const { dispatch } = this.props;
    dispatch({ type: 'dictValue/index', payload: record });
    dispatch({ type: 'dictValue/fetch', payload: { indexId: record.id } });
  };

  handleOpenValueModal = data => {
    const {
      dispatch,
      dictValue: { index },
    } = this.props;
    dispatch({ type: 'dictValue/openModal', payload: { ...data, parentId: index.id } });
  };

  handleSubmitValueModal = () => {
    const {
      dispatch,
      dictValue: { index },
    } = this.props;
    dispatch({ type: 'dictValue/fetch', payload: { indexId: index.id } });
  };

  render() {
    const {
      dictValue: { index },
    } = this.props;
    const indexName = index.name;
    return (
      <PageHeaderWrapper>
        <Row gutter={8}>
          <Col span={13}>
            <Card
              title="字典索引列表"
              extra={
                <Button type="primary" onClick={() => this.handleOpenIndexModal()}>
                  新建
                </Button>
              }
            >
              <DictIndexList
                onViewValues={record => {
                  this.handleViewIndexValues(record);
                }}
                onEdit={record => this.handleOpenIndexModal(record)}
              />
              <DictIndexModal onSubmit={this.handleSubmitIndexModal} />
            </Card>
          </Col>
          <Col span={11}>
            <Card
              title={`${indexName ? `${indexName}--` : ''}字典值列表`}
              extra={
                index.id ? (
                  <Button type="primary" onClick={() => this.handleOpenValueModal({})}>
                    新建
                  </Button>
                ) : null
              }
            >
              <DictValueList onEdit={record => this.handleOpenValueModal(record)} />
              <DictValueModal onSubmit={this.handleSubmitValueModal} />
            </Card>
          </Col>
        </Row>
      </PageHeaderWrapper>
    );
  }
}

export default Dict;
